package com.app.common.download

import android.app.ProgressDialog
import android.content.Context
import android.media.MediaScannerConnection
import android.widget.TextView
import com.app.common.R
import java.io.File

class DownloaderDialog(context: Context, saveDirectory: File, themeId:Int = 0) : ProgressDialog(context,themeId), Event {
    class DownloadInfo(val url:String,val fileName:String)
    interface Event{
        fun onDownloadSuccess(path: List<String>)
        fun onComplete()
    }

    private val downloader = Downloader()
    init {
        downloader.setDelegate(HttpDownloader(saveDirectory))
        setProgressStyle(STYLE_HORIZONTAL)
        setOnDismissListener {
            downloader.removeEvent(this)
            downloader.remove()
            scan()
            event?.onComplete()
            this.event = null
            release()
        }
        setButton(BUTTON_NEGATIVE,context.resources.getString(android.R.string.cancel)) { _, _ ->  }

    }
    var event:Event? = null
    private val complete = mutableListOf<Pair<String,String>>()
    private var first = true
    private var button: TextView? = null
    override fun show() {
        super.show()

        button = findViewById<TextView>(android.R.id.button2)
        button?.setText(android.R.string.cancel)
    }

    fun release(){
        downloader.release()
    }
    fun show(paths:List<DownloadInfo>, event: Event){
        this.event = event
        first = true
        complete.clear()
        setCancelable(false)
        downloader.removeEvent(this)
        downloader.addEvent(this)

        paths.forEach {
            downloader.add(it.url,it.fileName)
        }
        this.progress = 0
        setTitle(context.resources.getString(R.string.case_ui_core_downloader_title) + "...")
        show()
    }
    private fun scan(){
        if (complete.isEmpty()) {
            return
        }
        val localPaths = Array(complete.size){
            complete[it].second
        }
        println("============scan:${localPaths.joinToString()} $event")
        MediaScannerConnection.scanFile(context, localPaths, null, null)
        val paths = complete.map {
            it.first
        }
        event?.onDownloadSuccess(paths)
    }
    override fun onDownloadBegin(path: String, index: Int) {
        if(downloader.count <=1){
            setTitle(context.resources.getString(R.string.case_ui_core_downloader_title) )
        }else{
            setTitle(context.resources.getString(R.string.case_ui_core_downloader_title) + ":${index +1}/${downloader.count}")
        }

    }

    override fun onDownloadComplete(path: String, localPath: String, index: Int, isCancel: Boolean, error: Exception?, workCount: Int) {
        println("======onDownloadComplete:$path , $localPath,$isCancel ,$error")
        if (workCount == 0) {
            android.R.id.button1
            setTitle(context.resources.getString(R.string.case_ui_core_downloader_complete_title) )
            button?.setText(android.R.string.ok)
            setCancelable(true)
        }

        if (!isCancel && error == null) {
            complete+= path to localPath
        }
    }

    override fun onDownloading(path: String, index: Int, receiveSize: Long, size: Long, progress: Int) {
        this.progress = progress
    }
}